/*
 * @Author: xinyang3
 * @Date: 2022-03-11 17:33
 * @Descripttion: awesome description
 * @LastEditors: xinyang3
 * @LastEditTime: 2022-04-02 17:19
 */
import { createVNode, render } from "vue";
import LoadingConstructor from "./loading.vue";

const instances = [];
let seed = 1;

function Loading(options) {
  let idx = seed++;
  let props = Object.assign({}, options, {
    idx,
    clazz: `loading-index-${idx}`,
  });

  let container = document.createElement("div");
  let vm = createVNode(LoadingConstructor, props);

  vm.close = function (id) {
    render(null, container);
    container.remove();
    container = null;
    var index = instances.findIndex(({ vm }) => vm.props.idx == idx);
    instances.splice(index, 1);
  };
  render(vm, container);
  instances.push({ vm });
  document.body.appendChild(container.firstChild);

  return {
    vm,
  };
}

Loading.closeAll = () => {
  instances.forEach(({ vm }) => {
    vm.close && vm.close();
  });
};

export default Loading;
